package dbi.org.model;

import java.util.HashMap;
import java.util.LinkedHashMap;

import dbi.org.exception.KeyDoesntExistsException;
import dbi.org.exception.ReferenceDoesntExistsException;

public class Constraint {
	private String name = "";

	private LinkedHashMap<String, GroupKey> keys;
	private LinkedHashMap<String, Reference> references;

	public Constraint(String name) {
		this.name = name;
		keys = new LinkedHashMap<String, GroupKey>();
		references = new LinkedHashMap<String, Reference>();
	}

	public String getName() {
		return name;
	}

	public HashMap<String, GroupKey> getKeys() {
		return keys;
	}

	public HashMap<String, Reference> getReferences() {
		return references;
	}

	public void addSingleKeys(GroupKey gs) {

		if (!keys.containsKey(gs.getName())) {
			keys.put(gs.getName(), gs);
		}

	}

	public GroupKey getKey(String keyName) throws KeyDoesntExistsException {
		GroupKey k = null;

		if (keys.containsKey(keyName)) {
			k = keys.get(keyName);
		} else {
			throw new KeyDoesntExistsException(keyName);
		}

		return k;

	}
	
	public Reference getReference(String refName) throws ReferenceDoesntExistsException {
		Reference r = null;

		if (references.containsKey(refName)) {
			r = references.get(refName);
		} else {
			throw new ReferenceDoesntExistsException(refName);
		}

		return r;
	}

	public boolean addsingleReference(Reference ref) {
		if (!references.containsKey(ref.getName())) {
			references.put(ref.getName(), ref);
			return true;
		} else if(ref.fromGroup != null && ref.toGroup != null) {
			references.put(ref.getName(), ref);
			return true;
		}
		return false;
	}
	
	public void removeReference(String refName) throws ReferenceDoesntExistsException {
		Reference ref = getReference(refName);
		
		references.remove(ref.getName());
	}

}
